module ActiveBackground
  class Client    
    @@server = false
    
    def prepare
      connect unless @@server
      if @@server.terminated?
        raise "Server is being terminated"
      end
    end
    
    def connect(client_options = {})
      @client_options ||= client_options
      config = Configuration.new
      server = Server.new
      @@defaults = server.defaults
            
      # load configuration from rails config file,
      # or load file from local config file
      # if both don't exist default to internal defaults
      begin
        begin # try to load rails
          require File.dirname(__FILE__) + "/../../../../config/boot.rb"
          options = @@defaults.merge(config.load("#{RAILS_ROOT}/config/#{@@defaults[:config_file]}"))
        rescue Exception => e # loading of rails failed
          options = @@defaults.merge(config.load(File.dirname(__FILE__) + "/../config/#{@@defaults[:config_file]}"))
        end
      rescue Exception => e # loading of local file failed
        options = @@defaults
      end
            

      unless @client_options[:local]
        begin
          # the uri where we want to make our DRb available
          uri = "druby://#{options[:host]}:#{options[:port]}"
          DRb.start_service()
          @@server = DRbObject.new(nil, uri)
        rescue Exception => e
          raise 'Cannot connect to ' + uri + '. Please check your configuration \n\n' + e
        end
      else
        @@server = ActiveBackground::Manager.instance
      end
    end
            
    # using an instance of MiddleMan allows to use MiddleMan as Enumberable
    def each
      prepare
      jobs = @@server.get_jobs()
      
      jobs.each do |job|
        yield job
      end
    end

    def wait_for_server()
      @@server.wait()
    end
    
    def terminate_server
      @@server.terminate()
    end
  end
end